package cn.com.blueInfo.autoCode.vue;

import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author suxch
 * @since 2025/9/14 22:57
 */
@Component
public class CreateQueryVue {

    private static final String BASE_VUE_FILE_PATH = "D:\\Development Program\\ProjectCode_idea\\LanxiPavilion\\LanxiPavilion-parent" +
            "\\lanxi-pavilion-vite-vue3\\src\\views\\bpm\\";
    private static final Map<String, String> MODULE_MAP = Collections.unmodifiableMap(new HashMap<String, String>() {{
        put("bsn", "number");
        put("osm", "person");
        put("sys", "system");
        put("uniflow", "template");
    }});

    private static final String[] FIELDS = {"application_id", "create_time", "create_user_id", "deleted", "delete_time",
            "delete_user_id", "extend1", "extend2", "extend3", "id", "order_number", "remark", "status", "tenant_id",
            "update_time", "update_user_id"};

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void handler() {
        String querySql = "select table_name, table_comment from information_schema.`TABLES` where TABLE_SCHEMA = 'haiyuan_dev'";
        List<Map<String, Object>> resultData = jdbcTemplate.queryForList(querySql);

        List<FormVueFile> listVueFileList = new ArrayList<>();

        for (Map<String, Object> oneData : resultData) {
            String tableName = (String) oneData.get("table_name");
            String[] tableNames = tableName.split("_");

            FormVueFile listVueFile = new FormVueFile();
            String modulePath = MODULE_MAP.get(tableNames[1]);
            listVueFile.setFilePath(BASE_VUE_FILE_PATH.concat(modulePath).concat(File.separator));
            listVueFile.setFileContent(getFileContent(getScriptContent(tableName), getTemplateContent(tableName), getStyleContent()));
            listVueFile.setFileName(getFileName(tableNames));
            listVueFileList.add(listVueFile);
        }
        writeFile(listVueFileList);
    }

    private String getScriptContent(String tableName) {
        String querySql = "select COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT from information_schema.`COLUMNS` \n" +
                "where TABLE_SCHEMA = 'haiyuan_dev' " +
                "and TABLE_NAME = '" + tableName + "'";
        List<Map<String, Object>> resultData = jdbcTemplate.queryForList(querySql);
        String content =
                "import {ref} from \"vue\";\n" +
                        "\n" +
                        "const queryData = ref({\n";
        for (Map<String, Object> oneData : resultData) {
            String columnName = (String) oneData.get("COLUMN_NAME");
            if (isWriteColumn(columnName)) continue;
            columnName = getColumnName(columnName);

            content = content.concat("  " + columnName + ": \"\",\n");

        }
        content = content.concat("})");
        return content;
    }

    private String getTemplateContent(String tableName) {
        String querySql = "select COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT from information_schema.`COLUMNS` \n" +
                "where TABLE_SCHEMA = 'haiyuan_dev' " +
                "and TABLE_NAME = '" + tableName + "'";
        List<Map<String, Object>> resultData = jdbcTemplate.queryForList(querySql);
        String content = "";
        for (Map<String, Object> oneData : resultData) {
            String columnName = (String) oneData.get("COLUMN_NAME");
            if (isWriteColumn(columnName)) continue;
            columnName = getColumnName(columnName);
            String columnComment = (String) oneData.get("COLUMN_COMMENT");
            columnComment = columnComment.contains("：") ? columnComment.substring(0, columnComment.indexOf("：")) :
                    columnComment.contains("（") ? columnComment.substring(0, columnComment.indexOf("（")) : columnComment;

            content = content.concat("  <el-input v-model=\"queryData." + columnName + "\" style=\"width: 240px\" placeholder=\"请输入" + columnComment + "\" />\n");

        }
        return content;
    }

    private String getStyleContent() {
        return "";
    }

    private String getFileContent(String scriptContent, String templateContent, String styleContent) {
        return "<script setup>\n" +
                scriptContent + "\n" +
                "</script>\n" +
                "\n" +
                "<template>\n" +
                templateContent +
                "</template>\n" +
                "\n" +
                "<style scoped lang=\"scss\">\n" +
                styleContent + "\n" +
                "</style>";
    }

    private String getFileName(String[] tableNames) {
        String fileName = "";
        for (int t_i = 2, t_len = tableNames.length; t_i < t_len; t_i++) {
            String name = tableNames[t_i];
            fileName = fileName.concat(StringUtils.capitalize(name));
        }
        fileName = StringUtils.uncapitalize(fileName);
        return fileName.concat(File.separator).concat("Query.vue");
    }

    private void writeFile(List<FormVueFile> vueFileList) {
        try {
            for (FormVueFile vueFile : vueFileList) {
                String filePath = vueFile.getFilePath().concat(vueFile.getFileName());
                FileUtils.writeStringToFile(new File(filePath), vueFile.getFileContent(), StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Data
    private static class FormVueFile {
        private String fileName;
        private String filePath;
        private String fileContent;
    }

    private boolean isWriteColumn(String columnName) {
        for (String field : FIELDS) {
            if (field.equals(columnName))
                return true;
        }
        return false;
    }

    private String getColumnName(String columnName) {
        String[] columnNames = columnName.split("_");
        String resultName = "";
        for (String name : columnNames) {
            resultName = resultName.concat(StringUtils.capitalize(name));
        }
        resultName = StringUtils.uncapitalize(resultName);
        return resultName;
    }

}
